package com.news.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.news.common.CommonEnum;
import com.news.common.ResponseBean;
import com.news.common.ResultUtil;
import com.news.common.ToolsUtils;
import com.news.entity.NewsCategory;
import com.news.entity.SysNews;
import com.news.service.NewsCategoryService;
import com.news.service.SysNewsService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 新闻分类表 前端控制器
 * </p>
 *
 */
@Controller
@RequestMapping({"/category","/home/category"})
public class NewsCategoryController {

    private static  final Logger logger= LoggerFactory.getLogger(NewsCategoryController.class);

    private static final String page_prefix="news/category/";


    @Autowired
    SysNewsService newsService;

    @Autowired
    NewsCategoryService categoryService;

    /**
     * 跳到添加页面
     * @param model
     * @return
     */
    @RequestMapping("addPage")
    public String addPage(Model model){
        return page_prefix+"add";
    }

    //新闻分类添加
    @RequestMapping("add")
    @ResponseBody
    public ResponseBean addNews(NewsCategory category, HttpSession session){
        logger.debug("addNewsCategory:"+category);
        String name = category.getName();
        String code = category.getCode();
        QueryWrapper<NewsCategory> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("code",code).like("name",name);
        List<NewsCategory> list = categoryService.list(queryWrapper);
        if(!ToolsUtils.isEmpty(list)){
            return ResultUtil.error("名称或编码已经存在！");
        }
        boolean i = categoryService.save(category);
        logger.debug("保存后的NewsCategory:"+category);
        return ResultUtil.successData(category);
    }

    /**
     * 跳转到修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/editPage/{id}")
    public String editPage(@PathVariable Long id, Model model) {
        model.addAttribute("category", categoryService.getById(id));
        return page_prefix+"edit";
    }


    /**
     * 新闻分类修改
     * @param category
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public ResponseBean updateById(NewsCategory category,HttpSession session) {
        if (category == null||category.getId()==null) {
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        String name = category.getName();
        String code = category.getCode();
        QueryWrapper<NewsCategory> queryWrapper=new QueryWrapper<>();
        queryWrapper.like("code",code).like("name",name).ne("id",category.getId());
        List<NewsCategory> list = categoryService.list(queryWrapper);
        if(!ToolsUtils.isEmpty(list)){
            return ResultUtil.error("名称或编码已经存在！");
        }
        category.setUpdateTime(LocalDateTime.now());
        boolean i = categoryService.updateById(category);
        return ResultUtil.successData(category);
    }

    /**
     * 跳转列表页面
     * @return
     */
    @RequestMapping("/listPage")
    public String listPage() {
        return page_prefix+"list";
    }

    /**
     * 新闻分类列表查询
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param queryParam 查询参数
     * @param vagueParam 模糊参数
     * @return
     */
    @ApiOperation("获取新闻分类列表")
    @RequestMapping("/list/{pageNum}/{pageSize}")
    @ResponseBody
    public ResponseBean getList(@PathVariable Integer pageNum,@PathVariable Integer pageSize,
                                NewsCategory queryParam,String vagueParam) {
        logger.debug("查询新闻分类列表参数："+queryParam+",pageNum:"+pageNum+",pageSize:"+pageSize);
        QueryWrapper<NewsCategory> queryWrapper=new QueryWrapper<>();
//        模糊查询
        queryWrapper.like(!StringUtils.isEmpty(vagueParam),"code",vagueParam).or()
                .like(!StringUtils.isEmpty(vagueParam),"name",vagueParam);
        IPage<NewsCategory> indexPage = new Page<>(pageNum, pageSize);
        IPage<NewsCategory> listPage = categoryService.page(indexPage, queryWrapper);
        logger.debug("获取的新闻分类列表："+listPage);
        //获取新闻分类信息
        Map<String, Object> pageInfo = new HashMap<String, Object>();
        pageInfo.put("pageSize", listPage.getSize());
        pageInfo.put("pageNum", listPage.getCurrent());
        pageInfo.put("pages", listPage.getPages());
        pageInfo.put("total", listPage.getTotal());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("categoryList", listPage.getRecords());
        resultMap.put("pageInfo", pageInfo);
        return ResultUtil.successData(resultMap);
    }

    /**
     * 批量删除分类
     * @param idList
     * @return
     */
    @RequestMapping("deleteBatchByIds")
    @ResponseBody
    public ResponseBean deleteBatchByIds(@RequestParam List<Long> idList){
        logger.debug("deleteBatchByIds:"+idList);
        if(idList==null||idList.isEmpty()){
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        QueryWrapper<SysNews> queryWrapper=new QueryWrapper();
        for(Long id:idList){
            queryWrapper.eq("category_id",id);
            List<SysNews> list = newsService.list(queryWrapper);
            if(!ToolsUtils.isEmpty(list)){
                NewsCategory category = categoryService.getById(id);
                return ResultUtil.error("该分类"+category.getName()+"下有新闻，不可删除！");
            }
        }
        boolean delete = categoryService.removeByIds(idList);
        logger.debug("批量删除结果："+delete);
        return ResultUtil.success() ;
    }

    @RequestMapping("deleteById")
    @ResponseBody
    public ResponseBean deleteById(@RequestParam Long id){
        if(id==null||id<0){
            return ResultUtil.error(CommonEnum.BAD_PARAM);
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("category_id",id);
        List list = newsService.list(queryWrapper);
        if(!ToolsUtils.isEmpty(list)){
            return ResultUtil.error("该分类下有新闻，不可删除！");
        }
        boolean delete = categoryService.removeById(id);
        return ResultUtil.success() ;
    }
}
